const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';
const dbName = 'test001';
const collectionName = 'user001';

async function performCRUDOperations() {
    const client = await MongoClient.connect(url);
    console.log('Connected to MongoDB');

    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    try {
        // 插入数据
        /*const document = { name: 'John Doe', age: 25 };
        const insertResult = await collection.insertOne(document);
        console.log('Document inserted successfully');*/

        // 更新数据
        const filter = { name: 'John Doe' };
        const update = { $set: { age: 30 } };
        const updateResult = await collection.updateOne(filter, update);
        console.log('Document updated successfully');

        // 删除数据
        /*const deleteResult = await collection.deleteOne(filter);
        console.log('Document deleted successfully');*/

        // 查询数据
        const documents = await collection.find({}).toArray();
        console.log('Documents:', documents);
    } catch (err) {
        console.error('Error performing CRUD operations: ', err);
    } finally {
        // 断开连接
        client.close();
        console.log('Disconnected from MongoDB');
    }
}

performCRUDOperations();